package org.example.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.message.Message;
import org.apache.tomcat.util.security.MD5Encoder;
import org.example.Util.JwtUtil;
import org.example.controller.viewobject.UserVO;
import org.example.dataobject.UserDO;
import org.example.error.BusinessException;
import org.example.error.EmBusinessError;
import org.example.response.CommonReturnType;
import org.example.service.UserService;
import org.example.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.embedded.netty.NettyWebServer;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

@Controller("user")
@RequestMapping("/user")
//@CrossOrigin(origins = {"http://127.0.0.1:8081"},allowCredentials = "true",exposedHeaders = "Set-Cookie")//返回spring对应web请求单中，跨域
public class UserController extends BaseController{
    @Autowired
    private UserService userService;
    @Autowired//通过bean的方法注入，本质是一个pro
    private HttpServletRequest httpServletRequest;

    /**
     * @RequestMapping 用于将HTTP请求映射到控制器方法，此处专门处理 POST类型 的 /login 路径请求。
     * @param teiphon
     * @param password
     * @return
     * @throws BusinessException
     */
    //用户登录接口
@RequestMapping(value = "/login",method = RequestMethod.POST)
/**
 * 当你在 Controller 的方法上添加 @ResponseBody 时，
 * Spring 会将方法的返回值自动序列化为 JSON/XML 格式（取决于配置），
 * 并直接写入 HTTP 响应体，供客户端（如浏览器、移动端）解析。
 */
@ResponseBody
public CommonReturnType login(@RequestParam(name = "teiphon")String teiphon,
                              @RequestParam(name="password")String password) throws BusinessException {
    //入参校验
    if(org.apache.commons.lang3.StringUtils.isEmpty(teiphon)||
            StringUtils.isEmpty(password)){
        throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR);
    }
    //用户登录合法
    UserModel userModel=userService.vaildateLogin(teiphon,this.EncodeByMd5(password));
    //加入登录凭证加入到用户成功登录的session
    this.httpServletRequest.getSession().setAttribute("IS_LOGIN",true);
    this.httpServletRequest.getSession().setAttribute("LOGIN_USER",userModel);
    HttpSession session = httpServletRequest.getSession(true);
    session.setAttribute("LOGIN_USER", userModel);

    //生成JWT token
    String token = JwtUtil.generateToken(userModel);

    UserVO userVO=new UserVO();
    BeanUtils.copyProperties(userModel,userVO);
    Map<String, Object> result=new HashMap<>();
    result.put("user",userVO);
    result.put("token",token);
    return CommonReturnType.create(result);
}


    //用户注册接口
    @RequestMapping(value="/register",method=RequestMethod.POST)
    @ResponseBody
    public CommonReturnType register(@RequestParam(name = "teiphon")String teiphon,
              @RequestParam(name = "otpCode")String otpCode,
              @RequestParam(name = "name")String name,
              @RequestParam(name = "gender")Integer gender,
              @RequestParam(name = "age")Integer age, @RequestParam(name = "password")String password) throws BusinessException {
        //验证手机号和对应的otpCode相符合
        String inSessionOtpCode = (String) this.httpServletRequest.getSession().getAttribute(teiphon);
        if (!com.alibaba.druid.util.StringUtils.equals(otpCode, inSessionOtpCode)) {
            throw new BusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR, "短信验证码不符合");
        }
        //用户的注册流程
        UserModel userModel = new UserModel();
        userModel.setName(name);
        userModel.setGender(Byte.valueOf(String.valueOf(gender.intValue())));
        userModel.setAge(age);
        userModel.setTeiphon(teiphon);
        userModel.setEncrptPassword(this.EncodeByMd5(password));
        userModel.setRegisterMode("byphone");
        userService.register(userModel);
        return CommonReturnType.create(null);
    }

        public String EncodeByMd5(String str) {
            try {
                // 获取 MD5 摘要实例
                MessageDigest md5 = MessageDigest.getInstance("MD5");

                // 计算 MD5 哈希值
                byte[] md5Bytes = md5.digest(str.getBytes("UTF-8"));

                // 使用 java.util.Base64 进行编码
                Base64.Encoder encoder = Base64.getEncoder();
                String newstr = encoder.encodeToString(md5Bytes);

                return newstr;
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
                return null;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }


    //用户获取otp短信接口
    @RequestMapping(value="/getotp",method=RequestMethod.POST)
    @ResponseBody
    public CommonReturnType getOtp(@RequestParam(name="teiphon")String teiphon){
        //需要按照一定规则生成OTP验证码
        Random random=new Random();
        int randomInt=random.nextInt(99999);
        randomInt+=10000;
        String otpCode=String.valueOf(randomInt);

        //将OTP验证码同对应的手机号关联，使用httpsession的方式绑定手机号与OTPCDSODE
        httpServletRequest.getSession().setAttribute(teiphon,otpCode);
        System.out.println("teiphon="+teiphon+"&otpCode："+otpCode);
        //将OTP验证码通过短信通道发送给用户
        return CommonReturnType.create(null);
    }


    @ResponseBody
    @RequestMapping("/get")
    public CommonReturnType getUser(@RequestParam(name="id")Integer id) throws BusinessException {
        //调用service服务获取对应id的用户对象并返回给前端
        UserModel userModel = userService.getUserById(id);

        //若用户信息不存在
        if(userModel==null){
            throw new BusinessException(EmBusinessError.USER_NOT_EXIST);
        }
        //将核心领域模型用户对象转化为可供ui使用的viewOject
        UserVO userVO= converFromModel(userModel);
        //返回通用对象
        return CommonReturnType.create(userVO);//
    }
    private UserVO converFromModel(UserModel userModel){
        if(userModel==null){
            return null;
        }
        UserVO userVO=new UserVO();
        BeanUtils.copyProperties(userModel,userVO);
        return userVO;
    }

}
